
package com.crowdfunding.circle.discuss.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crowdfunding.circle.common.controller.BaseController;
import com.crowdfunding.circle.common.param.SessionUserInfo;
import com.crowdfunding.circle.discuss.entity.DiscussVO;
import com.crowdfunding.circle.discuss.param.DiscussParam;
import com.crowdfunding.circle.discuss.service.DiscussService;
import com.crowdfunding.circle.sensitiveword.SensitiveWordUtils;

/**
 * 评论信息Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class DiscussController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(DiscussController.class);

    @Autowired
    private DiscussService discussService;

    private final static String LIST_PAGE = "/discuss/discuss_list";

    private final static String VIEW_PAGE = "/discuss/view";

    private final static String UPDATE_PAGE = "/discuss/update";

    private static final String MY_LIST_PAGE = "/account/my_discuss";

    private static final String ADMIN_LIST_PAGE = "/admin/discuss_manage";

    @RequestMapping(value = "/check/discuss/toInsert")
    public ModelAndView intoInsert() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        DiscussVO discussVO = new DiscussVO();
        resultMap.put("discussVO", discussVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/discuss/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        DiscussVO discussVO = discussService.findById(id);
        resultMap.put("discussVO", discussVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/discuss/insert", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String insert(DiscussVO discussVO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (discussVO == null || StringUtils.isBlank(discussVO.getDiscussInfo())) {
            resultMap.put("result", false);
            resultMap.put("message", "评论内容不能为空");
            return JSONObject.toJSONString(resultMap);
        }

        if (discussVO.getDiscussInfo().length() < 5) {
            resultMap.put("result", false);
            resultMap.put("message", "评论内容最少为5个字");
            return JSONObject.toJSONString(resultMap);
        }

        if (StringUtils.isBlank(discussVO.getDiscussTargetId()) || discussVO.getDiscussType() == null) {
            resultMap.put("result", false);
            resultMap.put("message", "缺少评论对象信息");
            return JSONObject.toJSONString(resultMap);
        }
        
        if (SensitiveWordUtils.isContaintSensitiveWord(discussVO.getDiscussInfo(), 1)) {
            resultMap.put("result", false);
            resultMap.put("message", "评论内容中包含敏感词汇" + SensitiveWordUtils.getSensitiveWord(discussVO.getDiscussInfo(), 1) + "，请检查后再保存");
            return JSONObject.toJSONString(resultMap);
        }

        Object userInfoObj = session.getAttribute("sessionUserInfo");

        SessionUserInfo seUserInfo = null;

        if (userInfoObj == null) {
            resultMap.put("result", false);
            resultMap.put("message", "请先登录后再评论");
            return JSONObject.toJSONString(resultMap);
        } else {
            seUserInfo = (SessionUserInfo) userInfoObj;
        }

        try {
            discussVO.setDiscussId(UUID.randomUUID().toString());
            discussVO.setDiscussTime(new Date(System.currentTimeMillis()));
            discussVO.setPublishUser(seUserInfo.getUserId());
            discussVO.setUserName(seUserInfo.getUserName());

            Integer insertCount = discussService.insert(discussVO);
            if (insertCount != null && insertCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改评论信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改评论信息失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改评论信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改评论信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/admin/discuss/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = discussService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除评论信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除评论信息失败");
            }
        } catch (Exception e) {
            logger.error("删除评论信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除评论信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/uncheck/discuss/list", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public ModelAndView queryList(DiscussParam discussParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<DiscussVO> dataList = discussService.queryByPage(discussParam);
        resultMap.put("discussList", dataList);
        Integer discussType = discussParam.getDiscussType();
        if (discussType != null && (discussType == 1 || discussType == 3 || discussType == 4)) {
            List<Map<String, Object>> discussScoreCountList = discussService.queryDiscussScoreCount(discussParam);
            discussParam.setBadCount(0L);
            discussParam.setMediumCount(0L);
            discussParam.setGoodCount(0L);
            for (Map<String, Object> discussScoreCount : discussScoreCountList) {
                Long scoreCount = (Long) discussScoreCount.get("scoreCount");
                Integer discussScore = (Integer) discussScoreCount.get("discussScore");
                if (discussScore != null && discussScore == 1) {
                    discussParam.setBadCount(scoreCount);
                } else if (discussScore != null && discussScore == 2) {
                    discussParam.setMediumCount(scoreCount);
                } else if (discussScore != null && discussScore == 3) {
                    discussParam.setGoodCount(scoreCount);
                }
            }
        }
        resultMap.put("paramMap", discussParam);
        return new ModelAndView(LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/account/discuss/list", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public ModelAndView queryMyList(DiscussParam discussParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        discussParam.setPublishUser(seUser.getUserId());

        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> dataList = discussService.queryMyDiscussByPage(discussParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", discussParam);
        return new ModelAndView(MY_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/admin/discuss/list", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public ModelAndView queryAdminDiscussList(DiscussParam discussParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (discussParam.getDiscussType() == null || discussParam.getDiscussType() == 0) {
            discussParam.setDiscussType(1);
        }
        List<DiscussVO> dataList = discussService.queryByPage(discussParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", discussParam);
        return new ModelAndView(ADMIN_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/uncheck/discuss/view/{id}")
    public ModelAndView viewConfigInfo(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        DiscussVO discussVO = discussService.findById(id);
        resultMap.put("discussVO", discussVO);
        return new ModelAndView(VIEW_PAGE, resultMap);
    }
}
